<template>
  <div class="payment">
    <div class="container">
      <!-- 进度指示器 -->
      <div class="payment-progress">
        <div class="progress-step completed">
          <div class="step-number">✓</div>
          <div class="step-label">选择商品</div>
        </div>
        <div class="progress-line completed"></div>
        <div class="progress-step completed">
          <div class="step-number">✓</div>
          <div class="step-label">确认订单</div>
        </div>
        <div class="progress-line completed"></div>
        <div class="progress-step active">
          <div class="step-number">3</div>
          <div class="step-label">支付完成</div>
        </div>
      </div>

      <div class="payment-content">
        <!-- 订单信息卡片 -->
        <div class="order-card">
          <h2>💳 支付订单</h2>
          <div class="order-info">
            <div class="info-item">
              <span class="label">订单编号:</span>
              <span class="value">{{ orderNo }}</span>
            </div>
            <div class="info-item">
              <span class="label">支付金额:</span>
              <span class="value amount">¥{{ paymentAmount }}</span>
            </div>
            <div class="info-item">
              <span class="label">创建时间:</span>
              <span class="value">{{ formatDateTime(createTime) }}</span>
            </div>
          </div>
        </div>

        <!-- 支付方式选择 -->
        <div class="payment-methods">
          <h2>💰 选择支付方式</h2>
          <div class="methods-grid">
            <div 
              v-for="method in paymentMethods" 
              :key="method.id"
              class="method-card"
              :class="{ active: selectedMethod === method.id }"
              @click="selectMethod(method.id)"
            >
              <div class="method-icon">
                <img :src="method.icon" :alt="method.name" />
              </div>
              <div class="method-info">
                <h3>{{ method.name }}</h3>
                <p>{{ method.description }}</p>
                <div v-if="method.discount" class="discount-tag">
                  {{ method.discount }}
                </div>
              </div>
              <div class="method-radio">
                <input 
                  type="radio" 
                  :value="method.id" 
                  v-model="selectedMethod"
                  :id="`method-${method.id}`"
                />
                <label :for="`method-${method.id}`"></label>
              </div>
            </div>
          </div>
        </div>

        <!-- 支付安全提示 -->
        <div class="security-notice">
          <h2>🔒 支付安全</h2>
          <div class="security-content">
            <div class="security-item">
              <div class="security-icon">🛡️</div>
              <div class="security-text">
                <h4>SSL加密传输</h4>
                <p>您的支付信息通过SSL加密保护</p>
              </div>
            </div>
            <div class="security-item">
              <div class="security-icon">🔐</div>
              <div class="security-text">
                <h4>银行级安全</h4>
                <p>采用银行级别的安全防护措施</p>
              </div>
            </div>
            <div class="security-item">
              <div class="security-icon">⚡</div>
              <div class="security-text">
                <h4>快速到账</h4>
                <p>支付成功后立即确认订单</p>
              </div>
            </div>
          </div>
        </div>

        <!-- 倒计时提醒 -->
        <div class="countdown-notice" v-if="timeLeft > 0">
          <div class="countdown-content">
            <div class="countdown-icon">⏰</div>
            <div class="countdown-text">
              <h4>支付倒计时</h4>
              <p>请在 <span class="time">{{ formatTime(timeLeft) }}</span> 内完成支付，否则订单将自动取消</p>
            </div>
          </div>
          <div class="countdown-bar">
            <div class="countdown-progress" :style="{ width: progressWidth + '%' }"></div>
          </div>
        </div>

        <!-- 支付按钮 -->
        <div class="payment-actions">
          <button @click="goBack" class="btn btn-outline">
            ← 返回订单
          </button>
          <button 
            @click="processPayment" 
            class="btn btn-primary"
            :disabled="!selectedMethod || isProcessing || timeLeft <= 0"
            :class="{ loading: isProcessing }"
          >
            <span v-if="!isProcessing">立即支付 ¥{{ paymentAmount }}</span>
            <span v-else class="loading-content">
              <div class="loading-spinner"></div>
              正在支付...
            </span>
          </button>
        </div>
      </div>
    </div>

    <!-- 支付成功弹窗 -->
    <div v-if="showSuccessModal" class="success-modal" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="success-animation">
          <div class="checkmark">✓</div>
        </div>
        <h2>支付成功！</h2>
        <p>您的订单已支付成功，我们将尽快为您处理</p>
        <div class="modal-info">
          <div class="info-row">
            <span>订单编号:</span>
            <span>{{ orderNo }}</span>
          </div>
          <div class="info-row">
            <span>支付金额:</span>
            <span>¥{{ paymentAmount }}</span>
          </div>
          <div class="info-row">
            <span>支付时间:</span>
            <span>{{ formatDateTime(new Date()) }}</span>
          </div>
        </div>
        <div class="modal-actions">
          <button @click="viewOrder" class="btn btn-outline">查看订单</button>
          <button @click="goHome" class="btn btn-primary">返回首页</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useToastStore } from '@/stores/toast'
import AlipayIcon from '@/assets/images/alipay.svg'
import WechatIcon from '@/assets/images/wechatpay.svg'
import UnionpayIcon from '@/assets/images/unionpay.svg'
import CreditIcon from '@/assets/images/creditcard.svg'

const router = useRouter()
const route = useRoute()
const toast = useToastStore()

// 状态管理
const isProcessing = ref(false)
const showSuccessModal = ref(false)
const selectedMethod = ref('')
const timeLeft = ref(15 * 60) // 15分钟倒计时
const timer = ref(null)

// 订单信息
const orderNo = ref(route.query.orderNo || 'ORD' + Date.now())
const paymentAmount = ref(1680)
const createTime = ref(new Date())

// 支付方式
const paymentMethods = reactive([
  {
    id: 'alipay',
    name: '支付宝',
    description: '推荐使用，支持花呗分期',
    icon: AlipayIcon,
    discount: '立减5元'
  },
  {
    id: 'wechat',
    name: '微信支付',
    description: '微信用户首选支付方式',
    icon: WechatIcon,
    discount: null
  },
  {
    id: 'unionpay',
    name: '银联支付',
    description: '支持各大银行储蓄卡和信用卡',
    icon: UnionpayIcon,
    discount: null
  },
  {
    id: 'credit',
    name: '信用卡支付',
    description: '支持Visa、MasterCard等',
    icon: CreditIcon,
    discount: '免手续费'
  }
])

// 计算属性
const progressWidth = computed(() => {
  const totalTime = 15 * 60
  return (timeLeft.value / totalTime) * 100
})

// 格式化时间
const formatTime = (seconds) => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}

// 格式化日期时间
const formatDateTime = (date) => {
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 选择支付方式
const selectMethod = (methodId) => {
  selectedMethod.value = methodId
  
  const method = paymentMethods.find(m => m.id === methodId)
  toast.info({
    title: '支付方式已选择',
    message: `您选择了${method.name}`
  })
}

// 开始倒计时
const startCountdown = () => {
  timer.value = setInterval(() => {
    if (timeLeft.value > 0) {
      timeLeft.value--
    } else {
      clearInterval(timer.value)
      toast.error({
        title: '支付超时',
        message: '订单已自动取消，请重新下单'
      })
      setTimeout(() => {
        router.push('/cart')
      }, 2000)
    }
  }, 1000)
}

// 处理支付
const processPayment = async () => {
  if (!selectedMethod.value) {
    toast.warning({
      title: '请选择支付方式',
      message: '请先选择一种支付方式'
    })
    return
  }

  isProcessing.value = true

  try {
    // 模拟支付处理
    await new Promise(resolve => setTimeout(resolve, 3000))

    // 停止倒计时
    if (timer.value) {
      clearInterval(timer.value)
    }

    // 显示成功弹窗
    showSuccessModal.value = true

    toast.success({
      title: '支付成功',
      message: '订单支付完成，感谢您的购买！'
    })

  } catch (error) {
    toast.error({
      title: '支付失败',
      message: '支付过程中出现错误，请重试'
    })
  } finally {
    isProcessing.value = false
  }
}

// 返回订单确认页
const goBack = () => {
  router.push('/order-confirm')
}

// 关闭成功弹窗
const closeModal = () => {
  showSuccessModal.value = false
}

// 查看订单
const viewOrder = () => {
  router.push(`/orders/${orderNo.value}`)
}

// 返回首页
const goHome = () => {
  router.push('/')
}

// 组件挂载时开始倒计时
onMounted(() => {
  startCountdown()
})

// 组件卸载时清理定时器
onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value)
  }
})
</script>

<style scoped>
.payment {
  min-height: 100vh;
  background: #f8fafc;
  padding: 2rem 0;
}

.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 1rem;
}

/* 进度指示器 */
.payment-progress {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 1rem;
  padding: 2rem;
  background: white;
  border-radius: 12px;
  margin-bottom: 2rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.progress-step {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.5rem;
  opacity: 0.4;
  transition: all 0.3s ease;
}

.progress-step.active {
  opacity: 1;
  transform: scale(1.1);
}

.progress-step.completed {
  opacity: 1;
  color: #10b981;
}

.step-number {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #e5e7eb;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 16px;
  transition: all 0.3s ease;
}

.progress-step.active .step-number {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.progress-step.completed .step-number {
  background: #10b981;
  color: white;
}

.step-label {
  font-size: 14px;
  font-weight: 500;
  text-align: center;
}

.progress-line {
  width: 80px;
  height: 2px;
  background: #e5e7eb;
  border-radius: 1px;
}

.progress-line.completed {
  background: #10b981;
}

/* 支付内容 */
.payment-content {
  display: grid;
  gap: 2rem;
}

/* 通用卡片样式 */
.order-card,
.payment-methods,
.security-notice {
  background: white;
  border-radius: 12px;
  padding: 2rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.order-card h2,
.payment-methods h2,
.security-notice h2 {
  margin: 0 0 1.5rem 0;
  color: #1e293b;
  font-size: 1.25rem;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

/* 订单信息 */
.order-info {
  display: grid;
  gap: 1rem;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem 0;
  border-bottom: 1px solid #f1f5f9;
}

.info-item:last-child {
  border-bottom: none;
}

.info-item .label {
  color: #64748b;
  font-weight: 500;
}

.info-item .value {
  color: #1e293b;
  font-weight: 600;
}

.info-item .value.amount {
  color: #dc2626;
  font-size: 1.5rem;
}

/* 支付方式 */
.methods-grid {
  display: grid;
  gap: 1rem;
}

.method-card {
  display: grid;
  grid-template-columns: 60px 1fr auto;
  gap: 1rem;
  padding: 1.5rem;
  border: 2px solid #e2e8f0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fafafa;
}

.method-card:hover {
  border-color: #667eea;
  background: white;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.method-card.active {
  border-color: #667eea;
  background: #f0f4ff;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
}

.method-icon img {
  width: 60px;
  height: 60px;
  object-fit: contain;
}

.method-info h3 {
  margin: 0 0 0.5rem 0;
  color: #1e293b;
  font-size: 1.125rem;
  font-weight: 600;
}

.method-info p {
  margin: 0 0 0.5rem 0;
  color: #64748b;
  font-size: 0.875rem;
}

.discount-tag {
  display: inline-block;
  background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
  color: white;
  padding: 0.25rem 0.5rem;
  border-radius: 12px;
  font-size: 0.75rem;
  font-weight: 600;
}

.method-radio {
  display: flex;
  align-items: center;
  justify-content: center;
}

.method-radio input[type="radio"] {
  width: 20px;
  height: 20px;
  accent-color: #667eea;
}

/* 安全提示 */
.security-content {
  display: grid;
  gap: 1.5rem;
}

.security-item {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.security-icon {
  font-size: 2rem;
  width: 60px;
  text-align: center;
}

.security-text h4 {
  margin: 0 0 0.25rem 0;
  color: #1e293b;
  font-size: 1rem;
  font-weight: 600;
}

.security-text p {
  margin: 0;
  color: #64748b;
  font-size: 0.875rem;
}

/* 倒计时提醒 */
.countdown-notice {
  background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
  border: 1px solid #f59e0b;
  border-radius: 12px;
  padding: 1.5rem;
  position: relative;
  overflow: hidden;
}

.countdown-content {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 1rem;
}

.countdown-icon {
  font-size: 2rem;
}

.countdown-text h4 {
  margin: 0 0 0.25rem 0;
  color: #92400e;
  font-size: 1rem;
  font-weight: 600;
}

.countdown-text p {
  margin: 0;
  color: #78350f;
  font-size: 0.875rem;
}

.countdown-text .time {
  font-weight: 700;
  color: #dc2626;
  font-size: 1rem;
}

.countdown-bar {
  height: 4px;
  background: rgba(146, 64, 14, 0.2);
  border-radius: 2px;
  overflow: hidden;
}

.countdown-progress {
  height: 100%;
  background: linear-gradient(90deg, #dc2626 0%, #f59e0b 100%);
  transition: width 1s linear;
}

/* 支付按钮 */
.payment-actions {
  display: flex;
  gap: 1rem;
  justify-content: space-between;
  padding: 2rem;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.btn {
  padding: 0.875rem 2rem;
  border-radius: 8px;
  font-weight: 600;
  font-size: 1rem;
  cursor: pointer;
  transition: all 0.3s ease;
  border: none;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
}

.btn-outline {
  background: white;
  color: #667eea;
  border: 2px solid #667eea;
}

.btn-outline:hover {
  background: #667eea;
  color: white;
  transform: translateY(-2px);
}

.btn-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: 2px solid transparent;
  min-width: 200px;
}

.btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.btn.loading {
  cursor: not-allowed;
}

.loading-content {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top-color: white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 成功弹窗 */
.success-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 1rem;
}

.modal-content {
  background: white;
  border-radius: 16px;
  padding: 3rem;
  max-width: 500px;
  width: 100%;
  text-align: center;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);
}

.success-animation {
  margin-bottom: 2rem;
}

.checkmark {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  color: white;
  font-size: 3rem;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto;
  animation: checkmarkPop 0.6s ease-out;
}

@keyframes checkmarkPop {
  0% {
    transform: scale(0);
    opacity: 0;
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

.modal-content h2 {
  margin: 0 0 1rem 0;
  color: #1e293b;
  font-size: 1.5rem;
  font-weight: 700;
}

.modal-content p {
  margin: 0 0 2rem 0;
  color: #64748b;
  font-size: 1rem;
  line-height: 1.6;
}

.modal-info {
  background: #f8fafc;
  border-radius: 8px;
  padding: 1.5rem;
  margin-bottom: 2rem;
  text-align: left;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.5rem 0;
  border-bottom: 1px solid #e2e8f0;
}

.info-row:last-child {
  border-bottom: none;
}

.modal-actions {
  display: flex;
  gap: 1rem;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .payment-progress {
    flex-direction: column;
    gap: 1rem;
    padding: 1.5rem;
  }
  
  .progress-line {
    width: 2px;
    height: 40px;
  }
  
  .method-card {
    grid-template-columns: 1fr;
    text-align: center;
    gap: 1rem;
  }
  
  .payment-actions {
    flex-direction: column;
  }
  
  .btn {
    width: 100%;
  }
  
  .modal-actions {
    flex-direction: column;
  }
}
</style>